//
//  oldEncrypt.m
//  laonianbangfamily
//
//  Created by 勇拓 李 on 18/3/28.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldEncrypt.h"
#import "oldDes_Ecb.h"
#import "oldRegex.h"

@implementation oldEncrypt

+ (NSString *)encryptByDes:(NSDictionary *)dictionary
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSString *key in dictionary.allKeys) {
        NSString *value = [NSString stringWithFormat:@"%@", dictionary[key]];
        NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
        NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
        NSString *encodedValue = [value stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
        
        NSString *string = [NSString stringWithFormat:@"%@=%@", key, encodedValue];
        [array addObject:string];
    }
    
    NSArray *sortedArray = [oldEncrypt sortByAes:array];
    
    NSString *result = [oldEncrypt matchStringFromArray:sortedArray];
    
    NSString *lastString = [[oldDes_Ecb encryptUseDES:result key:DES_ECB_KEY] lowercaseString];
    
    NSString *md5String = [oldRegex md5:lastString];
    
    return md5String;
}


+ (NSArray *)sortByAes:(NSArray *)array
{
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    return sortArray;
}

+ (NSString *)matchStringFromArray:(NSArray *)array
{
    
    NSString *result = @"";
    for (int i = 0; i < [array count]; i++) {
        if (i != 0) {
            result = [NSString stringWithFormat:@"%@&%@", result, array[i]];
        }
        else
        {
            result = array[i];
        }
    }
    
    return result;
}

@end
